package io.wdb.handler;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.message.BasicNameValuePair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONObject;

import io.wdb.common.utils.HttpClientUtil;
import io.wdb.modules.activity.wx.entity.QueryUserResponse;
import io.wdb.modules.manager.sys.entity.SysUserEntity;

@Component
public class WechatMessageHandler {
	private final Logger logger = LoggerFactory.getLogger(getClass());
	@Value("${wx.appid}")
	private String appId;
	@Value("${wx.secret}")
	private String appSecurity;

    /**
     * 根据用户昵称获得用户的列表
     * @param nickname
     * @return 用户列表
     * @throws IOException 
     * @throws ClientProtocolException 
     */
    public List<SysUserEntity> getUsersByNickname(String nickname) throws ClientProtocolException, IOException {
        List<SysUserEntity> users = new ArrayList<>();
        //TODO 判断是否到达结尾
        for(SysUserEntity user : getUserList()) {
            if (user.getNickname().contains(nickname)) {
                users.add(user);
            }
        }
        return users;
    }
    /**
     * 
     * @Method:getAccessToken
     * @Description:从msgserve中获取accessToken
     * @Time 2018年3月21日 上午10:17:26
     * @author: Tom
     * @param appId
     * @return
     * @throws IOException 
     * @throws ClientProtocolException 
     */
    public String getAccessToken(String appId) throws ClientProtocolException, IOException {
    	List<NameValuePair> list = new ArrayList<>();
    	list.add(new BasicNameValuePair("", ""));
    	return HttpClientUtil.getPostBodyDataNameValuePair("", list);
    }
    
    /**
     * 只获取前1万个用户信息
     * @return 用户列表
     * @throws IOException 
     * @throws ClientProtocolException 
     */
    public List<SysUserEntity> getUserList() throws ClientProtocolException, IOException {
        List<SysUserEntity> users = new ArrayList<>();

        String url = "https://api.weixin.qq.com/cgi-bin/user/get?access_token=%s";
        
        String token = HttpClientUtil.getGetBody("http://47.100.117.234:9003/message_service/wx/getToken?app_id="+appId);
        logger.info("获取到的token为:\t"+token);
        //Token token = WxConfigUtil.getToken(appId, appSecurity, 3600);//this.getAccessToken(appId);
        url = String.format(url, token);
        
        String response = HttpClientUtil.getPostBodyDataNameValuePair(url, null);
        logger.info("拉取到的批量用户信息为：\t"+response);
        if (response != null) {
        	QueryUserResponse queryUserResponse = JSONObject.parseObject(response, QueryUserResponse.class);
            if (queryUserResponse != null && queryUserResponse.getData() != null) {
                for (String openId : queryUserResponse.getData().getOpenid()) {
                    users.add(getUserByOpenId(openId));
                }
            }
        }
        return users;
    }
    
    private String doPost(String url) {
       /* try {
            return Request.Post(url).connectTimeout(5000).socketTimeout(5000).execute().returnContent().asString(StandardCharsets.UTF_8);
        } catch (IOException e) {
            e.printStackTrace();
        }*/
        return null;
    }

    /**
     * 根据用户OpenId获得用户的信息
     * @param openId
     * @return 用户
     * @throws IOException 
     * @throws ClientProtocolException 
     */
    public SysUserEntity getUserByOpenId(String openId) throws ClientProtocolException, IOException {
        String url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=%s&openid=%s&lang=zh_CN";
        //Token token = WxConfigUtil.getToken(appId, appSecurity, 3600);
        String token = HttpClientUtil.getGetBody("http://47.100.117.234:9003/message_service/wx/getToken?app_id="+appId);
        logger.info("根据openId获取到的用户信息为:\t"+token);
        url = String.format(url, token, openId);

        String response = HttpClientUtil.getPostBodyDataNameValuePair(url, null);
        logger.info("从批量信息中根据OpenId获取到的用户信息为:\t"+response);
        if (response != null) {
        	WxUser user = JSONObject.parseObject(response, WxUser.class);
        	SysUserEntity sysUserEntity = new SysUserEntity();
        	sysUserEntity.setWxPublicOpenId(user.getOpenid());
        	sysUserEntity.setNickname(user.getNickname());
        	return sysUserEntity;
        } else {
        	return new SysUserEntity();
        }
    }

    private boolean isOpenIdExist(String openId) throws ClientProtocolException, IOException {
        String url = "https://api.weixin.qq.com/cgi-bin/user/get?access_token=%s";
        url = String.format(url, this.getAccessToken(url));

        /*String response = doPost(url);
        if (response != null) {
            QueryUserResponse userResponse = QueryUserResponse.fromJson(response);
            if (userResponse != null)
                if (Arrays.asList(userResponse.data.openid).contains(openId))
                    return true;
        }*/

        return false;
    }

}
